import React from 'react'
import {connect} from 'react-redux';
import '../assets/styles'
import ZTreeReact from "./ZTreeReact";
import treeIcon from '../assets/styles/img/tree'
import ContextMenu from "./ContextMenu";
import Scrollbars from './CustomScrollbars'
import enums from '../basic/enums'
import './jquery-vendor'
import IndexService from "../service/IndexService";
import windowUtil from "../basic/utils/windowUtil";
import Tooltip from '@material-ui/core/Tooltip'
import Const from "../Const";


/**
 * 名称：文件树
 * 创建人：Dada.
 * 创建时间：2021年07月22日20:23:40
 */
class FileTree extends React.Component {
    isInit = false;
    treeRef = null;
    treeObj = null;
    indexService = new IndexService();
    state = {
        fileList: [
            // {
            //    _id: 1,
            //     name: '资料包',
            //     extName: '',
            //     openTime: new Date(),
            //     isActive: false,
            //     isSave: false,
            //     pId: '',
            //     type: enums.FileType.package,
            //     content: '',
            //     icon: treeIcon.base
            // }, {
            //    _id: 11,
            //     name: '张三.png',
            //     extName: '.png',
            //     openTime: new Date(),
            //     isActive: true,
            //     isSave: false,
            //     pId: 1,
            //     type: 'file',
            //     content: 'zs',
            //     icon: treeIcon.file
            // }, {
            //    _id: 12,
            //     name: '李四.cs',
            //     extName: '.cs',
            //     openTime: new Date(),
            //     isActive: true,
            //     isSave: false,
            //     pId: 1,
            //     type: 'file',
            //     content: 'ls',
            //     icon: treeIcon.file
            // }, {
            //    _id: 13,
            //     name: '王五.txt',
            //     extName: '.txt',
            //     openTime: new Date(),
            //     isActive: true,
            //     isSave: false,
            //     pId: 1,
            //     type: 'file',
            //     content: 'ww',
            //     icon: treeIcon.file
            // }, {
            //    _id: 14,
            //     name: '着六.txt',
            //     extName: '.txt',
            //     openTime: new Date(),
            //     isActive: true,
            //     isSave: false,
            //     pId: 1,
            //     type: 'file',
            //     content: 'zl',
            //     icon: treeIcon.file
            // }, {
            //    _id: 15,
            //     name: '袁⑦.txt',
            //     extName: '.txt',
            //     openTime: new Date(),
            //     isActive: true,
            //     isSave: false,
            //     pId: 1,
            //     type: 'file',
            //     content: 'yq',
            //     icon: treeIcon.file
            // }, {
            //    _id: 2,
            //     name: '数据包',
            //     extName: '',
            //     openTime: new Date(),
            //     isActive: false,
            //     isSave: false,
            //     pId: '',
            //     type: 'filePackage',
            //     content: '123',
            //     icon: treeIcon.base
            // },
            // {
            //    _id: 21,
            //     name: '张三.txt',
            //     extName: '.txt',
            //     openTime: new Date(),
            //     isActive: true,
            //     isSave: false,
            //     pId: 2,
            //     type: 'file',
            //     content: 'zs1',
            //     icon: treeIcon.file
            // },
            // {
            //    _id: 22,
            //     name: '李四.txt',
            //     extName: '.txt',
            //     openTime: new Date(),
            //     isActive: true,
            //     isSave: false,
            //     pId: 2,
            //     type: 'file',
            //     content: '123',
            //     icon: treeIcon.file
            // },
            // {
            //    _id: 23,
            //     name: '王五.txt',
            //     extName: '.txt',
            //     openTime: new Date(),
            //     isActive: true,
            //     isSave: false,
            //     pId: 2,
            //     type: 'file',
            //     content: '123',
            //     icon: treeIcon.file
            // },
            // {
            //    _id: 24,
            //     name: '着六.txt',
            //     extName: '.txt',
            //     openTime: new Date(),
            //     isActive: true,
            //     isSave: false,
            //     pId: 2,
            //     type: 'file',
            //     content: '123',
            //     icon: treeIcon.file
            // },
            // {
            //    _id: 25,
            //     name: '袁⑦.txt',
            //     extName: '.txt',
            //     openTime: new Date(),
            //     isActive: true,
            //     isSave: false,
            //     pId: 2,
            //     type: 'file',
            //     content: '123',
            //     icon: treeIcon.file
            // }
        ]
    }

    onLoadMenuList = (event) => {
        const {toElement} = event;
        //树上点击
        const pZtree = $(toElement).parents('.ztree');
        const nodeId = $(toElement).parents('li').data('id');
        let generalMenuList = [
            {
                name: '新建文件',
                isLine: false,
                isBan: false,
                event: (item, e) => {
                    windowUtil.showXTextDialog({
                        title: '请输入',
                        tip: '请输入名称:',
                        callback: (res) => {
                            let newNode = this.indexService.addItem(nodeId, res, enums.FileType.file, '');
                            //add tree node
                            let zTree = this.getZTreeObj();
                            let node = zTree.getNodesByParam('_id', newNode.pId)[0];
                            let nNode = this.indexService.procItemToZtreeNode(newNode);
                            zTree.addNodes(node, -1, nNode);
                            //打开刚刚新建的
                            let zNode = zTree.getNodesByParam('_id', nNode._id)[0];
                            this.props.onOpenFile(zNode);
                            //选中
                            this.getZTreeObj().selectNode(zNode);
                        }
                    })
                }
            }, {
                name: '新建目录',
                isLine: false,
                isBan: false,
                event: (item, e) => {
                    windowUtil.showXTextDialog({
                        title: '请输入',
                        tip: '请输入名称:',
                        callback: (res) => {
                            let newNode = this.indexService.addItem(nodeId, res, enums.FileType.package);
                            //add tree node
                            let zTree = this.getZTreeObj();
                            let node = zTree.getNodesByParam('_id', newNode.pId)[0];
                            let nNode = this.indexService.procItemToZtreeNode(newNode);
                            zTree.addNodes(node, -1, nNode);
                        }
                    })
                }
            }
        ];
        if (pZtree[0]) {
            return [].concat(generalMenuList, [
                {
                    name: '打开',
                    isLine: false,
                    event: (item) => {
                        const zTree = this.getZTreeObj();
                        let node = zTree.getNodesByParam('_id', nodeId)[0];
                        if (!node) {
                            alert('数据异常，无法打开');
                        }
                        if (node.type === 'filePackage') {
                            zTree.expandNode(node, true, false, true);
                        } else {
                            this.props.onOpenFile(node);
                        }
                    }
                }, {
                    name: '重命名',
                    isLine: false,
                    event: (item) => {
                        let zTree = this.getZTreeObj();
                        let node = zTree.getNodesByParam('_id', nodeId)[0];
                        windowUtil.showXTextDialog({
                            title: '请输入',
                            tip: '请输入名称:',
                            value: node.name,
                            callback: (res) => {
                                this.indexService.renameFile(nodeId, res);
                                node.name = res;
                                node.extName = res.substr(res.lastIndexOf('.'));
                                zTree.updateNode(node, false);
                                this.props.updateNode(this.indexService.findNodeById(nodeId));
                            }
                        })
                    }
                }, {
                    name: '删除',
                    isLine: false,
                    event: (item) => {
                        let node = this.indexService.findNodeById(nodeId);
                        let childList = this.indexService.getList(node._id + '/');
                        windowUtil.showXTipDialog({
                            tip: node.type == enums.FileType.file && childList.length == 0 ? '确定要删除吗?' : '<span style="color: red">该文件夹下的文件会被移动到根目录，不会被删除。</span>确定要删除该文件夹吗?',
                            callback: () => {
                                let zNode = this.getZTreeObj().getNodesByParam('_id', nodeId)[0];
                                this.indexService.deleteNode(nodeId);
                                if (zNode.type == enums.FileType.package) {
                                    this.treeObj.removeNode(zNode);
                                    this.initTreeList();
                                } else {
                                    this.props.deleteNode(nodeId);
                                    this.treeObj.removeNode(zNode);
                                }
                            }
                        })
                    }
                }, {
                    name: '属性',
                    isLine: false,
                    isBan: true,
                    event: (item) => {

                    }
                }, {
                    name: '历史记录',
                    isBan: true,
                    isLine: false,
                    event: (item) => {

                    }
                }
            ])
        }
        return [].concat(generalMenuList, [])
    }

    componentDidMount() {
        let cb = () => {
            if (this.isInit) {
                return;
            }
            this.isInit = true;
            this.treeObj = this.treeRef.getZTreeObj();
            this.props.setZtreeObject(this.treeObj);
            this.indexService.generationDefaultFileData();
            this.initTreeList()
        }
        window.onPluginReady(cb);
        window.onPluginEnter(cb);
    }

    initTreeList = () => {
        if (!this.treeObj) {
            this.treeObj = this.treeRef.getZTreeObj();
            this.props.setZtreeObject(this.treeObj);
        }
        let treeList = this.indexService.findFileTree();
        this.props.setFileList(treeList);
        this.deleteTreeAllNode();
        setTimeout(() => {
            this.treeObj.addNodes(null, -1, treeList, false);
            this.treeObj.expandAll(true)
        }, 100)
    }

    deleteTreeAllNode = () => {
        let rootList = this.treeObj.getNodesByParam('pId', null, null);
        rootList.map(item => {
            this.treeObj.removeChildNodes(item);
            this.treeObj.removeNode(item);
        })
    }

    onDblClick = (e, treeId, treeNode) => {
        if (treeNode.type === enums.FileType.package) {
            return;
        }
        this.props.onOpenFile(treeNode);
    }

    getZTreeObj = () => {
        return this.treeRef.getZTreeObj();
    }

    treeToolsEvent = {
        localSelect: () => {
            let list = this.props.openList;
            list.forEach(item => {
                if (item.isActive) {
                    let treeObj = this.getZTreeObj();
                    treeObj.selectNode(treeObj.getNodesByParam('_id', item._id)[0]);
                    return;
                }
            })
        }, min: () => {
        }, setting: () => {
            this.initTreeList()
        }, collapse: () => {
            this.getZTreeObj().expandAll(false);
        }, expand: () => {
            this.getZTreeObj().expandAll(true);
        }
    }

    render() {
        let {className, style} = this.props;
        return (
            <div className={className} style={style}>
                <div className='tree-tools'>
                    <div className='tools-left'>文件列表</div>
                    <div className='tools-right'>
                        {/*<span className='btn iconfont icon-zuixiaohua'*/}
                        {/*      onClick={this.treeToolsEvent.min.bind(this)}/>*/}
                        <Tooltip title='刷新' placement='bottom'>
                            <span className='btn iconfont icon-shuaxin'
                                  onClick={this.treeToolsEvent.setting.bind(this)}/>
                        </Tooltip>
                        <Tooltip title='全部收缩' placement='bottom'>
                        <span className='btn iconfont icon-collapse'
                              onClick={this.treeToolsEvent.collapse.bind(this)}/>
                        </Tooltip>
                        <Tooltip title='全部展开' placement='bottom'>
                        <span className='btn iconfont icon-expand'
                              onClick={this.treeToolsEvent.expand.bind(this)}/>
                        </Tooltip>
                        <Tooltip title='定位' placement='bottom'>
                        <span className='btn iconfont icon-dingwei'
                              onClick={this.treeToolsEvent.localSelect.bind(this)}/>
                        </Tooltip>
                    </div>
                </div>
                <ContextMenu className='hb100' onLoadMenuList={this.onLoadMenuList}>
                    <Scrollbars className='file-tree-warp hb100'>
                        <ZTreeReact
                            id='fileTree'
                            onDblClick={this.onDblClick}
                            ref={ref => this.treeRef = ref}
                            treeData={this.state.fileList}/>
                    </Scrollbars>
                </ContextMenu>
            </div>
        );
    }
}

export default connect(
    (state, props) => {
        return state
    },
    (dispatch) => {
        return {
            setFileList: function (listData) {
                dispatch({
                    type: 'setFileList',
                    data: listData
                })
            },
            onOpenFile: function (item) {
                dispatch({
                    type: 'openFile',
                    data: item
                })
            },
            addNode: function (item) {
                dispatch({
                    type: 'addNode',
                    data: item
                })
            },
            deleteNode: (id) => {
                dispatch({
                    type: 'deleteNode',
                    data: id
                })
            },
            updateNode: function (item) {
                dispatch({
                    type: 'updateNode',
                    data: item
                })
            },
            setZtreeObject: (ztreeObj) => {
                dispatch({
                    type: 'setZtreeObject',
                    data: ztreeObj
                })
            }
        }
    }
)(FileTree)
